<!DOCTYPE html>
<html>
<head>
  <title>👥 客户中心</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
  <style>
    :root {
      --primary-color: #4361ee;
      --secondary-color: #3f37c9;
      --success-color: #4cc9f0;
      --info-color: #4895ef;
      --warning-color: #f72585;
      --danger-color: #e63946;
      --light-color: #f8f9fa;
      --dark-color: #212529;
      --pending-color: #FF9800;
      --processing-color: #2196F3;
      --completed-color: #4CAF50;
      --cancelled-color: #F44336;
      --refunded-color: #9E9E9E;
      --on-hold-color: #9C27B0;
      --failed-color: #607D8B;
      --row-even-bg: #f8f9fa;
      --row-odd-bg: #ffffff;
    }
    
    body {
      background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
      min-height: 100vh;
      max-width: 1440px;
      margin: 0 auto;
      font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    }
    
    .header-gradient {
      background: linear-gradient(120deg, var(--primary-color), var(--secondary-color));
      color: white;
      border-radius: 15px;
      box-shadow: 0 10px 30px rgba(0,0,0,0.15);
      margin-bottom: 25px;
      padding: 25px;
    }
    
    .card {
      border-radius: 15px;
      box-shadow: 0 10px 30px rgba(0,0,0,0.08);
      border: none;
      margin-bottom: 25px;
      transition: all 0.3s;
    }
    
    .card:hover {
      box-shadow: 0 15px 40px rgba(0,0,0,0.15);
      transform: translateY(-3px);
    }
    
    .status-card {
      border-radius: 12px;
      transition: all 0.3s ease;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
      height: 100%;
    }
    
    .status-card:hover {
      transform: translateY(-5px);
      box-shadow: 0 15px 30px rgba(0,0,0,0.2);
    }
    
    .table-container {
      background: white;
      border-radius: 15px;
      overflow: hidden;
      box-shadow: 0 10px 30px rgba(0,0,0,0.08);
    }
    
    .table th {
      background: linear-gradient(120deg, var(--primary-color), var(--secondary-color));
      color: white;
      font-weight: 600;
      padding: 15px;
    }
    
    .table td {
      padding: 15px;
      vertical-align: middle;
    }
    
    /* 交替行颜色 */
    .table-striped tbody tr:nth-of-type(even) {
      background-color: var(--row-even-bg);
    }
    
    .table-striped tbody tr:nth-of-type(odd) {
      background-color: var(--row-odd-bg);
    }
    
    .table-hover tbody tr:hover {
      background-color: #e9f7fe;
      transform: scale(1.01);
      transition: all 0.2s;
    }
    
    .badge-pending {
      background-color: var(--pending-color) !important;
    }
    
    .badge-processing {
      background-color: var(--processing-color) !important;
    }
    
    .badge-completed {
      background-color: var(--completed-color) !important;
    }
    
    .badge-cancelled {
      background-color: var(--cancelled-color) !important;
    }
    
    .badge-refunded {
      background-color: var(--refunded-color) !important;
    }
    
    .badge-on-hold {
      background-color: var(--on-hold-color) !important;
    }
    
    .badge-failed {
      background-color: var(--failed-color) !important;
    }
    
    .btn-gradient {
      background: linear-gradient(120deg, var(--primary-color), var(--info-color));
      border: none;
      color: white;
      font-weight: 600;
      padding: 10px 20px;
      border-radius: 8px;
      transition: all 0.3s;
      box-shadow: 0 4px 15px rgba(67, 97, 238, 0.3);
    }
    
    .btn-gradient:hover {
      background: linear-gradient(120deg, var(--secondary-color), var(--primary-color));
      color: white;
      transform: translateY(-2px);
      box-shadow: 0 6px 20px rgba(67, 97, 238, 0.4);
    }
    
    .btn-success {
      background: linear-gradient(120deg, #28a745, #20c997);
      border: none;
      color: white;
      font-weight: 600;
      padding: 10px 20px;
      border-radius: 8px;
      transition: all 0.3s;
      box-shadow: 0 4px 15px rgba(40, 167, 69, 0.3);
    }
    
    .btn-success:hover {
      background: linear-gradient(120deg, #20c997, #28a745);
      transform: translateY(-2px);
      box-shadow: 0 6px 20px rgba(40, 167, 69, 0.4);
    }
    
    .search-card {
      background: white;
      border-radius: 15px;
      box-shadow: 0 10px 30px rgba(0,0,0,0.08);
      padding: 25px;
      margin-bottom: 25px;
    }
    
    .form-control, .form-select {
      height: 46px;
      border: 1px solid #dee2e6;
      border-radius: 8px;
      padding: 10px 15px;
      transition: all 0.3s;
    }
    
    .form-control:focus, .form-select:focus {
      border-color: var(--primary-color);
      box-shadow: 0 0 0 0.2rem rgba(67, 97, 238, 0.15);
      outline: none;
    }
    
    .input-group-text {
      background: #e9ecef;
      border: 1px solid #dee2e6;
      border-radius: 8px 0 0 8px;
      color: #495057;
      min-width: 45px;
      text-align: center;
    }
    
    .pagination .page-link {
      color: var(--primary-color);
      border: 1px solid #dee2e6;
      transition: all 0.3s;
    }
    
    .pagination .page-link:hover {
      background-color: var(--primary-color);
      color: white;
      border-color: var(--primary-color);
    }
    
    .pagination .active .page-link {
      background-color: var(--primary-color);
      border-color: var(--primary-color);
    }
    
    .customer-card {
      cursor: pointer;
      transition: all 0.2s;
    }
    
    .customer-card:hover {
      background-color: #e9f7fe !important;
    }
    
    .nav-link {
      color: rgba(255, 255, 255, 0.8) !important;
      font-weight: 500;
      transition: all 0.3s;
      border-radius: 5px;
      margin: 0 5px;
    }
    
    .nav-link:hover, .nav-link.active {
      color: white !important;
      background-color: rgba(255, 255, 255, 0.1);
    }
    
    .dropdown-toggle::after {
      margin-left: 0.5em;
    }
    
    .filter-clear-btn {
      background: linear-gradient(120deg, #6c757d, #495057);
      border: none;
      color: white;
      font-weight: 600;
      padding: 10px 20px;
      border-radius: 8px;
      transition: all 0.3s;
      box-shadow: 0 4px 15px rgba(108, 117, 125, 0.3);
    }
    
    .filter-clear-btn:hover {
      background: linear-gradient(120deg, #495057, #6c757d);
      transform: translateY(-2px);
      box-shadow: 0 6px 20px rgba(108, 117, 125, 0.4);
    }
    
    .avatar-placeholder {
      width: 50px;
      height: 50px;
      border-radius: 50%;
      background: linear-gradient(135deg, var(--primary-color), var(--info-color));
      display: flex;
      align-items: center;
      justify-content: center;
      color: white;
      font-weight: bold;
      font-size: 1rem;
      margin-right: 15px;
      flex-shrink: 0;
    }
    
    .customer-info h5 {
      margin-bottom: 0.25rem;
      font-weight: 600;
      color: #333;
    }
    
    .contact-column {
      min-width: 120px;
    }
    
    .contact-value {
      font-weight: 500;
      font-size: 0.9rem;
      color: #333;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
    
    .stat-item {
      text-align: center;
      padding: 0.5rem;
    }
    
    .stat-value {
      font-weight: 700;
      font-size: 1.1rem;
      color: var(--primary-color);
    }
    
    @media (max-width: 768px) {
      .customer-card .row {
        flex-direction: column;
      }
      
      .avatar-placeholder {
        margin-bottom: 10px;
      }
      
      .stat-item {
        padding: 0.25rem;
      }
    }
  </style>
</head>
<body class="p-4">
  <div class="container-fluid">
    <div class="header-gradient">
      <div class="d-flex justify-content-between align-items-center">
        <div>
          <h1 class="mb-0"><i class="fas fa-users me-3"></i>👥 客户中心（共 {{ total_customers }} 个客户）</h1>
          <p class="mb-0 opacity-75">管理所有客户信息</p>
        </div>
        <div class="d-flex align-items-center">
          <nav class="navbar navbar-expand navbar-dark me-4">
            <div class="navbar-nav">
              <a class="nav-link" href="/"><i class="fas fa-home me-1"></i> 系统首页</a>
              <a class="nav-link" href="/orders"><i class="fas fa-list me-1"></i> 订单管理</a>
              <a class="nav-link active" href="/customers"><i class="fas fa-users me-1"></i> 客户管理</a>
              {% if current_user and current_user.role == "root" %}
              <a class="nav-link" href="/users"><i class="fas fa-user-cog me-1"></i> 用户管理</a>
              {% endif %}
            </div>
          </nav>
          <div class="text-end">
            <div>
              <a href="/export-customers" class="btn btn-light">
                <i class="fas fa-file-export me-1"></i> 导出客户
              </a>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 搜索和筛选功能 -->
    <div class="search-card">
      <h5 class="mb-4"><i class="fas fa-filter me-2"></i>筛选条件</h5>
      <form id="searchForm" class="row g-3">
        <div class="col-md-3">
          <label for="searchCustomer" class="form-label">客户姓名/邮箱</label>
          <div class="input-group">
            <span class="input-group-text"><i class="fas fa-user"></i></span>
            <input type="text" class="form-control" id="searchCustomer" placeholder="搜索客户姓名或邮箱" oninput="filterCustomers()">
          </div>
        </div>
        <div class="col-md-2">
          <label for="searchCountry" class="form-label">国家</label>
          <div class="input-group">
            <span class="input-group-text"><i class="fas fa-flag"></i></span>
            <select class="form-select" id="searchCountry" onchange="filterCustomers()">
              <option value="">所有国家</option>
              {% for country in unique_countries %}
                <option value="{{ country }}">{{ country | country_name }}</option>
              {% endfor %}
            </select>
          </div>
        </div>
        <div class="col-md-2">
          <label for="searchCity" class="form-label">城市</label>
          <div class="input-group">
            <span class="input-group-text"><i class="fas fa-city"></i></span>
            <input type="text" class="form-control" id="searchCity" placeholder="搜索城市" oninput="filterCustomers()">
          </div>
        </div>
        <div class="col-md-3">
          <label for="searchPhone" class="form-label">电话号码</label>
          <div class="input-group">
            <span class="input-group-text"><i class="fas fa-phone"></i></span>
            <input type="text" class="form-control" id="searchPhone" placeholder="搜索电话号码" oninput="filterCustomers()">
          </div>
        </div>
        <div class="col-md-2 d-flex align-items-end">
          <button type="button" class="filter-clear-btn w-100" onclick="clearFilter()">
            <i class="fas fa-broom me-1"></i> 清除筛选
          </button>
        </div>
      </form>
    </div>

    <!-- 客户统计块 -->
    <div class="row mb-4" id="customerStats">
      <div class="col-md-4 col-6 mb-4">
        <div class="status-card p-3 rounded text-center shadow-sm">
          <div class="fs-2 fw-bold text-success" id="premiumCustomerCount">{{ premium_customers or 0 }}</div>
          <div class="small">
            <i class="fas fa-star me-1"></i> 优质客户
          </div>
        </div>
      </div>
      <div class="col-md-4 col-6 mb-4">
        <div class="status-card p-3 rounded text-center shadow-sm">
          <div class="fs-2 fw-bold text-primary" id="normalCustomerCount">{{ normal_customers or 0 }}</div>
          <div class="small">
            <i class="fas fa-user me-1"></i> 一般客户
          </div>
        </div>
      </div>
      <div class="col-md-4 col-6 mb-4">
        <div class="status-card p-3 rounded text-center shadow-sm">
          <div class="fs-2 fw-bold text-danger" id="poorCustomerCount">{{ poor_customers or 0 }}</div>
          <div class="small">
            <i class="fas fa-exclamation-triangle me-1"></i> 劣质客户
          </div>
        </div>
      </div>
    </div>

    <script>
      // 初始化时更新客户统计数据
      document.addEventListener('DOMContentLoaded', function() {
        // 页面加载完成后，从页面数据初始化统计信息
        initializeCustomerStats();
      });
      
      // 从页面数据初始化客户统计信息
      function initializeCustomerStats() {
        // 这个函数在页面初次加载时不需要做任何事情，
        // 因为统计数据已经在模板渲染时正确设置了
        // 只有在Ajax请求更新数据时才需要调用updateCustomerStats函数
      }
    </script>

    <!-- 客户列表 -->
    <div class="table-container">
      <table class="table table-striped table-hover mb-0">
        <thead>
          <tr>
            <th>客户信息</th>
            <th style="width: 200px;">电子邮箱</th>
            <th style="width: 150px;">联系电话</th>
            <th class="text-center" style="width: 100px;">订单数量</th>
            <th class="text-end" style="width: 100px;">消费总额</th>
            <th class="text-center" style="width: 100px;">最近购买</th>
            <th class="text-center" style="width: 100px;">客户质量</th>
          </tr>
        </thead>
        <tbody id="customersContainer">
          {% for customer in customers %}
          <tr class="customer-card" onclick="window.location.href='/customer/{{ customer.email or customer.full_name }}'">
            <td>
              <div class="d-flex align-items-center">
                <div class="avatar-placeholder me-3">
                  {% if customer.first_name or customer.last_name %}
                    {{ (customer.first_name|first if customer.first_name else '') + (customer.last_name|first if customer.last_name else '') }}
                  {% else %}
                    {{ customer.full_name|first if customer.full_name else 'U' }}
                  {% endif %}
                </div>
                <div class="customer-info">
                  <h5 class="mb-1">
                    {% if customer.first_name or customer.last_name %}
                      {{ customer.first_name }} {{ customer.last_name }}
                    {% else %}
                      {{ customer.full_name }}
                    {% endif %}
                  </h5>
                  <div class="d-flex flex-wrap gap-1">
                    {% if customer.country %}
                      <span class="badge bg-light text-dark">{{ customer.country }}</span>
                    {% endif %}
                    {% if customer.city %}
                      <span class="badge bg-light text-dark">{{ customer.city }}</span>
                    {% endif %}
                  </div>
                </div>
              </div>
            </td>
            <td>
              <div class="contact-value">
                {% if customer.email %}
                  {{ customer.email }}
                {% else %}
                  -
                {% endif %}
              </div>
            </td>
            <td>
              <div class="contact-value">
                {% if customer.phone %}
                  {{ customer.phone | format_phone(customer.country) }}
                {% else %}
                  -
                {% endif %}
              </div>
            </td>
            <td class="text-center">
              <div class="stat-value">{{ customer.total_orders }}</div>
            </td>
            <td class="text-end">
              <div class="stat-value">{{ "%.2f"|format(customer.total_spent) }} {{ customer.common_currency }}</div>
            </td>
            <td class="text-center">
              <div class="stat-value">
                {% if customer.last_order_date %}
                  {{ customer.last_order_date.strftime('%Y-%m-%d %H:%M') if customer.last_order_date else '-' }}
                {% else %}
                  -
                {% endif %}
              </div>
            </td>
            <td class="text-center">
              <div class="stat-value">
                {% if customer.customer_quality == 'premium' %}
                  <span class="badge bg-success">优质</span>
                {% elif customer.customer_quality == 'normal' %}
                  <span class="badge bg-primary">一般</span>
                {% elif customer.customer_quality == 'poor' %}
                  <span class="badge bg-danger">劣质</span>
                {% else %}
                  <span class="badge bg-secondary">未知</span>
                {% endif %}
              </div>
            </td>
          </tr>
          {% endfor %}
        </tbody>
      </table>
    </div>

    <!-- 分页控件 -->
    {% if pagination.pages > 1 %}
    <nav aria-label="客户分页" class="mt-4">
      <ul class="pagination justify-content-center">
        <!-- 上一页 -->
        {% if pagination.has_prev %}
          <li class="page-item">
            <a class="page-link" href="?page={{ pagination.prev_num }}&per_page={{ per_page }}" aria-label="上一页">
              <span aria-hidden="true">&laquo;</span>
            </a>
          </li>
        {% else %}
          <li class="page-item disabled">
            <span class="page-link">&laquo;</span>
          </li>
        {% endif %}

        <!-- 页码 -->
        {% for page_num in pagination.iter_pages() %}
          {% if page_num %}
            {% if page_num != pagination.page %}
              <li class="page-item">
                <a class="page-link" href="?page={{ page_num }}&per_page={{ per_page }}">{{ page_num }}</a>
              </li>
            {% else %}
              <li class="page-item active">
                <span class="page-link">{{ page_num }}</span>
              </li>
            {% endif %}
          {% else %}
            <li class="page-item disabled">
              <span class="page-link">…</span>
            </li>
          {% endif %}
        {% endfor %}

        <!-- 下一页 -->
        {% if pagination.has_next %}
          <li class="page-item">
            <a class="page-link" href="?page={{ pagination.next_num }}&per_page={{ per_page }}" aria-label="下一页">
              <span aria-hidden="true">&raquo;</span>
            </a>
          </li>
        {% else %}
          <li class="page-item disabled">
            <span class="page-link">&raquo;</span>
          </li>
        {% endif %}
      </ul>
    </nav>
    
    <!-- 分页信息 -->
    <div class="text-center text-muted mt-2">
      共 {{ total_customers }} 个客户，当前第 {{ pagination.page }} 页，共 {{ pagination.pages }} 页
    </div>
    {% endif %}

  </div>

  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
  <script src="https://kit.fontawesome.com/a076d05399.js" crossorigin="anonymous"></script>
  <script>
    // 获取国家中文名称的函数
    function getCountryName(countryCode) {
      if (!countryCode) return '-';
      const countryCodesToNames = {
        'AF': '阿富汗',
        'AX': '奥兰群岛',
        'AL': '阿尔巴尼亚',
        'DZ': '阿尔及利亚',
        'AS': '美属萨摩亚',
        'AD': '安道尔',
        'AO': '安哥拉',
        'AI': '安圭拉',
        'AQ': '南极洲',
        'AG': '安提瓜和巴布达',
        'AR': '阿根廷',
        'AM': '亚美尼亚',
        'AW': '阿鲁巴',
        'AU': '澳大利亚',
        'AT': '奥地利',
        'AZ': '阿塞拜疆',
        'BS': '巴哈马',
        'BH': '巴林',
        'BD': '孟加拉国',
        'BB': '巴巴多斯',
        'BY': '白俄罗斯',
        'BE': '比利时',
        'BZ': '伯利兹',
        'BJ': '贝宁',
        'BM': '百慕大',
        'BT': '不丹',
        'BO': '玻利维亚',
        'BQ': '荷兰加勒比区',
        'BA': '波斯尼亚和黑塞哥维那',
        'BW': '博茨瓦纳',
        'BV': '布韦岛',
        'BR': '巴西',
        'IO': '英属印度洋领地',
        'BN': '文莱',
        'BG': '保加利亚',
        'BF': '布基纳法索',
        'BI': '布隆迪',
        'CV': '佛得角',
        'KH': '柬埔寨',
        'CM': '喀麦隆',
        'CA': '加拿大',
        'KY': '开曼群岛',
        'CF': '中非共和国',
        'TD': '乍得',
        'CL': '智利',
        'CN': '中国',
        'CX': '圣诞岛',
        'CC': '科科斯（基林）群岛',
        'CO': '哥伦比亚',
        'KM': '科摩罗',
        'CG': '刚果（布）',
        'CD': '刚果（金）',
        'CK': '库克群岛',
        'CR': '哥斯达黎加',
        'CI': '科特迪瓦',
        'HR': '克罗地亚',
        'CU': '古巴',
        'CW': '库拉索',
        'CY': '塞浦路斯',
        'CZ': '捷克',
        'DK': '丹麦',
        'DJ': '吉布提',
        'DM': '多米尼克',
        'DO': '多米尼加共和国',
        'EC': '厄瓜多尔',
        'EG': '埃及',
        'SV': '萨尔瓦多',
        'GQ': '赤道几内亚',
        'ER': '厄立特里亚',
        'EE': '爱沙尼亚',
        'ET': '埃塞俄比亚',
        'FK': '福克兰群岛',
        'FO': '法罗群岛',
        'FJ': '斐济',
        'FI': '芬兰',
        'FR': '法国',
        'GF': '法属圭亚那',
        'PF': '法属波利尼西亚',
        'TF': '法属南方和南极领地',
        'GA': '加蓬',
        'GM': '冈比亚',
        'GE': '格鲁吉亚',
        'DE': '德国',
        'GH': '加纳',
        'GI': '直布罗陀',
        'GR': '希腊',
        'GL': '格陵兰',
        'GD': '格林纳达',
        'GP': '瓜德罗普',
        'GU': '关岛',
        'GT': '危地马拉',
        'GG': '根西',
        'GN': '几内亚',
        'GW': '几内亚比绍',
        'GY': '圭亚那',
        'HT': '海地',
        'HM': '赫德岛和麦克唐纳群岛',
        'VA': '梵蒂冈',
        'HN': '洪都拉斯',
        'HK': '香港',
        'HU': '匈牙利',
        'IS': '冰岛',
        'IN': '印度',
        'ID': '印度尼西亚',
        'IR': '伊朗',
        'IQ': '伊拉克',
        'IE': '爱尔兰',
        'IM': '马恩岛',
        'IL': '以色列',
        'IT': '意大利',
        'JM': '牙买加',
        'JP': '日本',
        'JE': '泽西',
        'JO': '约旦',
        'KZ': '哈萨克斯坦',
        'KE': '肯尼亚',
        'KI': '基里巴斯',
        'KP': '朝鲜',
        'KR': '韩国',
        'KW': '科威特',
        'KG': '吉尔吉斯斯坦',
        'LA': '老挝',
        'LV': '拉脱维亚',
        'LB': '黎巴嫩',
        'LS': '莱索托',
        'LR': '利比里亚',
        'LY': '利比亚',
        'LI': '列支敦士登',
        'LT': '立陶宛',
        'LU': '卢森堡',
        'MO': '澳门',
        'MK': '北马其顿',
        'MG': '马达加斯加',
        'MW': '马拉维',
        'MY': '马来西亚',
        'MV': '马尔代夫',
        'ML': '马里',
        'MT': '马耳他',
        'MH': '马绍尔群岛',
        'MQ': '马提尼克',
        'MR': '毛里塔尼亚',
        'MU': '毛里求斯',
        'YT': '马约特',
        'MX': '墨西哥',
        'FM': '密克罗尼西亚',
        'MD': '摩尔多瓦',
        'MC': '摩纳哥',
        'MN': '蒙古',
        'ME': '黑山',
        'MS': '蒙特塞拉特',
        'MA': '摩洛哥',
        'MZ': '莫桑比克',
        'MM': '缅甸',
        'NA': '纳米比亚',
        'NR': '瑙鲁',
        'NP': '尼泊尔',
        'NL': '荷兰',
        'NC': '新喀里多尼亚',
        'NZ': '新西兰',
        'NI': '尼加拉瓜',
        'NE': '尼日尔',
        'NG': '尼日利亚',
        'NU': '纽埃',
        'NF': '诺福克岛',
        'MP': '北马里亚纳群岛',
        'NO': '挪威',
        'OM': '阿曼',
        'PK': '巴基斯坦',
        'PW': '帕劳',
        'PS': '巴勒斯坦',
        'PA': '巴拿马',
        'PG': '巴布亚新几内亚',
        'PY': '巴拉圭',
        'PE': '秘鲁',
        'PH': '菲律宾',
        'PN': '皮特凯恩群岛',
        'PL': '波兰',
        'PT': '葡萄牙',
        'PR': '波多黎各',
        'QA': '卡塔尔',
        'RE': '留尼汪',
        'RO': '罗马尼亚',
        'RU': '俄罗斯',
        'RW': '卢旺达',
        'BL': '圣巴泰勒米',
        'SH': '圣赫勒拿、阿森松和特里斯坦-达库尼亚',
        'KN': '圣基茨和尼维斯',
        'LC': '圣卢西亚',
        'MF': '法属圣马丁',
        'PM': '圣皮埃尔和密克隆',
        'VC': '圣文森特和格林纳丁斯',
        'WS': '萨摩亚',
        'SM': '圣马力诺',
        'ST': '圣多美和普林西比',
        'SA': '沙特阿拉伯',
        'SN': '塞内加尔',
        'RS': '塞尔维亚',
        'SC': '塞舌尔',
        'SL': '塞拉利昂',
        'SG': '新加坡',
        'SX': '荷属圣马丁',
        'SK': '斯洛伐克',
        'SI': '斯洛文尼亚',
        'SB': '所罗门群岛',
        'SO': '索马里',
        'ZA': '南非',
        'GS': '南乔治亚和南桑威奇群岛',
        'SS': '南苏丹',
        'ES': '西班牙',
        'LK': '斯里兰卡',
        'SD': '苏丹',
        'SR': '苏里南',
        'SJ': '斯瓦尔巴和扬马延',
        'SZ': '斯威士兰',
        'SE': '瑞典',
        'CH': '瑞士',
        'SY': '叙利亚',
        'TW': '台湾',
        'TJ': '塔吉克斯坦',
        'TZ': '坦桑尼亚',
        'TH': '泰国',
        'TL': '东帝汶',
        'TG': '多哥',
        'TK': '托克劳',
        'TO': '汤加',
        'TT': '特立尼达和多巴哥',
        'TN': '突尼斯',
        'TR': '土耳其',
        'TM': '土库曼斯坦',
        'TC': '特克斯和凯科斯群岛',
        'TV': '图瓦卢',
        'UG': '乌干达',
        'UA': '乌克兰',
        'AE': '阿联酋',
        'GB': '英国',
        'US': '美国',
        'UM': '美国本土外小岛屿',
        'UY': '乌拉圭',
        'UZ': '乌兹别克斯坦',
        'VU': '瓦努阿图',
        'VE': '委内瑞拉',
        'VN': '越南',
        'VG': '英属维尔京群岛',
        'VI': '美属维尔京群岛',
        'WF': '瓦利斯和富图纳',
        'EH': '西撒哈拉',
        'YE': '也门',
        'ZM': '赞比亚',
        'ZW': '津巴布韦'
      };
      return countryCodesToNames[countryCode.toUpperCase()] || countryCode;
    }

    // 格式化电话号码的函数
    function formatPhone(phone, countryCode) {
      if (!phone) return '-';
      
      // 这里可以添加电话号码格式化逻辑
      // 为简化起见，我们直接返回电话号码
      return phone;
    }

    // 搜索和筛选功能
    let searchTimeout;

    function filterCustomers() {
      // Show loading state
      const tbody = document.getElementById('customersContainer');
      tbody.innerHTML = '<tr><td colspan="7" class="text-center"><div class="spinner-border text-primary" role="status"><span class="visually-hidden">Loading...</span></div></td></tr>';
      
      // Clear previous timeout
      clearTimeout(searchTimeout);
      
      // Set new timeout to avoid frequent requests
      searchTimeout = setTimeout(() => {
        const customer = document.getElementById('searchCustomer').value;
        const country = document.getElementById('searchCountry').value;
        const city = document.getElementById('searchCity').value;
        const phone = document.getElementById('searchPhone').value;
        
        // Build query parameters
        const params = new URLSearchParams();
        if (customer) params.append('customer', customer);
        if (country) params.append('country', country);
        if (city) params.append('city', city);
        if (phone) params.append('phone', phone);
        
        // Send API request with authentication
        fetch(`/api/customers?${params.toString()}`, {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json',
            'X-Requested-With': 'XMLHttpRequest'
          }
        })
          .then(response => {
            if (!response.ok) {
              throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response.json();
          })
          .then(data => {
            updateCustomerTable(data.customers);
            // Update customer count display in title
            const titleElement = document.querySelector('h1.mb-0');
            if (titleElement) {
              const baseTitle = '👥 客户中心';
              titleElement.innerHTML = `<i class="fas fa-users me-3"></i>${baseTitle}（共 ${data.count} 个客户）`;
            }
            
            // Update customer stats
            updateCustomerStats(data.customer_stats);
          })
          .catch(error => {
            console.error('Search error:', error);
            tbody.innerHTML = '<tr><td colspan="7" class="text-center text-danger">加载数据出错，请稍后重试</td></tr>';
          });
      }, 300); // 300ms delay
    }

    function clearFilter() {
      document.getElementById('searchCustomer').value = '';
      document.getElementById('searchCountry').value = '';
      document.getElementById('searchCity').value = '';
      document.getElementById('searchPhone').value = '';
      
      // Reload all customers
      filterCustomers();
    }

    function updateCustomerTable(customers) {
      const tbody = document.getElementById('customersContainer');
      if (!tbody) return;
      
      if (customers.length === 0) {
        tbody.innerHTML = '<tr><td colspan="7" class="text-center text-muted">暂无客户数据</td></tr>';
        return;
      }
      
      let html = '';
      customers.forEach(customer => {
        // 处理客户姓名显示
        let customerName = '';
        if (customer.first_name || customer.last_name) {
          customerName = `${customer.first_name || ''} ${customer.last_name || ''}`.trim();
        } else {
          customerName = customer.full_name || '未知客户';
        }
        
        // 处理国家显示
        let countryDisplay = '';
        if (customer.country) {
          countryDisplay = `<span class="badge bg-light text-dark">${getCountryName(customer.country)}</span>`;
        }
        
        // 处理城市显示
        let cityDisplay = '';
        if (customer.city) {
          cityDisplay = `<span class="badge bg-light text-dark">${customer.city}</span>`;
        }
        
        // 处理客户质量显示
        let qualityDisplay = '';
        if (customer.customer_quality === 'premium') {
          qualityDisplay = '<span class="badge bg-success">优质</span>';
        } else if (customer.customer_quality === 'normal') {
          qualityDisplay = '<span class="badge bg-primary">一般</span>';
        } else if (customer.customer_quality === 'poor') {
          qualityDisplay = '<span class="badge bg-danger">劣质</span>';
        } else {
          qualityDisplay = '<span class="badge bg-secondary">未知</span>';
        }
        
        html += `
          <tr class="customer-card" onclick="window.location.href='/customer/${encodeURIComponent(customer.email || customer.full_name)}'">
            <td>
              <div class="d-flex align-items-center">
                <div class="avatar-placeholder me-3">
                  ${customer.first_name || customer.last_name ? 
                    (customer.first_name?.[0] || '') + (customer.last_name?.[0] || '') : 
                    customer.full_name?.[0] || 'U'}
                </div>
                <div class="customer-info">
                  <h5 class="mb-1">${customerName}</h5>
                  <div class="d-flex flex-wrap gap-1">
                    ${countryDisplay}
                    ${cityDisplay}
                  </div>
                </div>
              </div>
            </td>
            <td>
              <div class="contact-value">
                ${customer.email || '-'}
              </div>
            </td>
            <td>
              <div class="contact-value">
                ${customer.formatted_phone || customer.phone || '-'}
              </div>
            </td>
            <td class="text-center">
              <div class="stat-value">${customer.total_orders}</div>
            </td>
            <td class="text-end">
              <div class="stat-value">${customer.total_spent.toFixed(2)} ${customer.common_currency}</div>
            </td>
            <td class="text-center">
              <div class="stat-value">
                ${customer.last_order_date ? new Date(customer.last_order_date).toLocaleString('zh-CN') : '-'}
              </div>
            </td>
            <td class="text-center">
              <div class="stat-value">
                ${qualityDisplay}
              </div>
            </td>
          </tr>
        `;
      });
      
      tbody.innerHTML = html;
    }

    function updateCustomerStats(stats) {
      if (stats) {
        document.getElementById('premiumCustomerCount').textContent = stats.premium || 0;
        document.getElementById('normalCustomerCount').textContent = stats.normal || 0;
        document.getElementById('poorCustomerCount').textContent = stats.poor || 0;
      }
    }

    // 滚动加载相关变量
    let isLoading = false;
    let currentPage = 1;
    let totalPages = 1;
    let hasMoreData = true;

    // 滚动加载函数
    function loadMoreCustomers() {
      if (isLoading || !hasMoreData) return;
      
      isLoading = true;
      currentPage++;
      
      // 显示加载指示器
      const loadingIndicator = document.createElement('tr');
      loadingIndicator.innerHTML = '<td colspan="7" class="text-center"><div class="spinner-border text-primary" role="status"><span class="visually-hidden">Loading...</span></div></td>';
      loadingIndicator.id = 'loading-indicator';
      document.getElementById('customersContainer').appendChild(loadingIndicator);
      
      // 构建查询参数
      const params = new URLSearchParams();
      params.append('page', currentPage);
      params.append('per_page', 20);
      
      // 获取当前筛选条件
      const customer = document.getElementById('searchCustomer').value;
      const country = document.getElementById('searchCountry').value;
      const city = document.getElementById('searchCity').value;
      const phone = document.getElementById('searchPhone').value;
      
      if (customer) params.append('customer', customer);
      if (country) params.append('country', country);
      if (city) params.append('city', city);
      if (phone) params.append('phone', phone);
      
      // 发送Ajax请求
      fetch(`/api/customers?${params.toString()}`, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
          'X-Requested-With': 'XMLHttpRequest'
        }
      })
      .then(response => {
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
        return response.json();
      })
      .then(data => {
        // 移除加载指示器
        const loadingIndicator = document.getElementById('loading-indicator');
        if (loadingIndicator) {
          loadingIndicator.remove();
        }
        
        // 更新分页信息
        totalPages = data.total_pages;
        hasMoreData = data.has_next;
        
        // 添加新数据到表格
        const tbody = document.getElementById('customersContainer');
        data.customers.forEach(customer => {
          // 处理客户姓名显示
          let customerName = '';
          if (customer.first_name || customer.last_name) {
            customerName = `${customer.first_name || ''} ${customer.last_name || ''}`.trim();
          } else {
            customerName = customer.full_name || '未知客户';
          }
          
          // 处理国家显示
          let countryDisplay = '';
          if (customer.country) {
            countryDisplay = `<span class="badge bg-light text-dark">${getCountryName(customer.country)}</span>`;
          }
          
          // 处理城市显示
          let cityDisplay = '';
          if (customer.city) {
            cityDisplay = `<span class="badge bg-light text-dark">${customer.city}</span>`;
          }
          
          // 处理客户质量显示
          let qualityDisplay = '';
          if (customer.customer_quality === 'premium') {
            qualityDisplay = '<span class="badge bg-success">优质</span>';
          } else if (customer.customer_quality === 'normal') {
            qualityDisplay = '<span class="badge bg-primary">一般</span>';
          } else if (customer.customer_quality === 'poor') {
            qualityDisplay = '<span class="badge bg-danger">劣质</span>';
          } else {
            qualityDisplay = '<span class="badge bg-secondary">未知</span>';
          }
          
          const row = document.createElement('tr');
          row.className = 'customer-card';
          row.onclick = () => window.location.href = `/customer/${encodeURIComponent(customer.email || customer.full_name)}`;
          row.innerHTML = `
            <td>
              <div class="d-flex align-items-center">
                <div class="avatar-placeholder me-3">
                  ${customer.first_name || customer.last_name ? 
                    (customer.first_name?.[0] || '') + (customer.last_name?.[0] || '') : 
                    customer.full_name?.[0] || 'U'}
                </div>
                <div class="customer-info">
                  <h5 class="mb-1">${customerName}</h5>
                  <div class="d-flex flex-wrap gap-1">
                    ${countryDisplay}
                    ${cityDisplay}
                  </div>
                </div>
              </div>
            </td>
            <td>
              <div class="contact-value">
                ${customer.email || '-'}
              </div>
            </td>
            <td>
              <div class="contact-value">
                ${customer.formatted_phone || customer.phone || '-'}
              </div>
            </td>
            <td class="text-center">
              <div class="stat-value">${customer.total_orders}</div>
            </td>
            <td class="text-end">
              <div class="stat-value">${customer.total_spent.toFixed(2)} ${customer.common_currency}</div>
            </td>
            <td class="text-center">
              <div class="stat-value">
                ${customer.last_order_date ? new Date(customer.last_order_date).toLocaleString('zh-CN') : '-'}
              </div>
            </td>
            <td class="text-center">
              <div class="stat-value">
                ${qualityDisplay}
              </div>
            </td>
          </tr>
        `;
          
          tbody.appendChild(row);
        });
      })
      .catch(error => {
        // 移除加载指示器
        const loadingIndicator = document.getElementById('loading-indicator');
        if (loadingIndicator) {
          loadingIndicator.remove();
        }
        
        console.error('加载更多客户失败:', error);
        // 显示错误信息
        const errorRow = document.createElement('tr');
        errorRow.innerHTML = '<td colspan="7" class="text-center text-danger">加载更多客户失败，请稍后重试</td>';
        document.getElementById('customersContainer').appendChild(errorRow);
        
        // 恢复加载状态
        isLoading = false;
      })
      .finally(() => {
        // 恢复加载状态
        isLoading = false;
      });
    }

    // 检查是否需要加载更多数据
    function checkScroll() {
      const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
      const scrollHeight = document.documentElement.scrollHeight;
      const clientHeight = document.documentElement.clientHeight;
      
      // 当滚动到距离底部100px时加载更多数据
      if (scrollTop + clientHeight >= scrollHeight - 100) {
        loadMoreCustomers();
      }
    }

    // 页面加载完成后初始化
    document.addEventListener('DOMContentLoaded', function() {
      // 页面加载完成后，从页面数据初始化统计信息
      initializeCustomerStats();
      // 添加滚动事件监听器
      window.addEventListener('scroll', checkScroll);
    });
  </script>
</body>
</html>
